package tn.orange.canreminder;

import java.util.Collections;
import java.util.List;

import tn.orange.canreminder.adapter.MatchAdapter;
import tn.orange.canreminder.helper.CalendrierHelper;
import tn.orange.canreminder.helper.CompetitionHelper;
import tn.orange.canreminder.model.Competition;
import tn.orange.canreminder.singleton.CompetitionSingleton;
import tn.orange.canreminder.sort.CompetitionComparator;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SlidingDrawer;
import android.widget.Spinner;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;

public class DashboardActivity extends Activity {

	private Button slideHandleButton;
	private SlidingDrawer slidingDrawer;

	private ListView listView;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.dashboard);

		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		boolean notif = preferences.getBoolean("notification", false);
		if (notif == true) {
			Intent intent = new Intent(this, ServiceCompetition.class);
			startService(intent);
		}
		slideHandleButton = (Button) findViewById(R.id.handle);
		slidingDrawer = (SlidingDrawer) findViewById(R.id.drawer);
		slidingDrawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {

			@Override
			public void onDrawerOpened() {
				// slideHandleButton.setBackgroundResource(R.drawable.openarrow);
				listView = (ListView) findViewById(R.id.content);
				CompetitionAsyncTask asyncTask = new CompetitionAsyncTask();
				asyncTask.execute();
			}
		});

		slidingDrawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {

			@Override
			public void onDrawerClosed() {

			}
		});

	}

	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.option:
			Intent intent2 = new Intent(DashboardActivity.this,
					ConfigActivity.class);
			startActivity(intent2);
			return true;
		case R.id.favoris:
			Intent intent = new Intent(DashboardActivity.this,
					ListFavoritePlaceActivity.class);
			startActivity(intent);
			return true;
		case R.id.apropos:
			Intent intent1 = new Intent(DashboardActivity.this,
					AProposActivity.class);
			startActivity(intent1);
			return true;

		}
		return false;
	}

	public void OnMatchClick(View v) {
		Intent intent = new Intent(this, ListMatchActivity.class);
		startActivity(intent);
	}

	public void OnPlacesClick(View v) {
		Intent intent = new Intent(this, ListPlacesCategory.class);
		startActivity(intent);
	}

	public void OnEquipeClick(View v) {
		Intent intent = new Intent(this, ListEquipeActivity.class);
		startActivity(intent);
	}

	public void OnChayMayFoot(View v) {
		Intent browserIntent = new Intent(Intent.ACTION_VIEW,
				Uri.parse("http://foot.orange.tn"));
		startActivity(browserIntent);
	}

	private class CompetitionAsyncTask extends
			AsyncTask<Void, Void, List<Competition>> {
		private final ProgressDialog dialog = new ProgressDialog(
				DashboardActivity.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Veuillez patienter...");
			this.dialog.setCancelable(false);
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected List<Competition> doInBackground(final Void... args) {

			List<Competition> competitions;
			List<Competition> newCompetitions = null;
			try {
				competitions = CompetitionSingleton.getInstance();
				CompetitionComparator comparator = new CompetitionComparator();

				newCompetitions = CompetitionHelper.getLastCompetitions();
				Collections.sort(newCompetitions, comparator);
			} catch (Exception e) {
				// TODO: handle exception
				cancel(false);
			}

			return newCompetitions;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			showErrorDialog("Problème de connexion ");

		}

		// can use UI thread here
		protected void onPostExecute(List<Competition> competitions) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
				MatchAdapter adapter = new MatchAdapter(DashboardActivity.this,
						competitions);
				listView.setAdapter(adapter);

			}
		}
	}

	private void showErrorDialog(String message) {
		AlertDialog alertDialog = new AlertDialog.Builder(
				DashboardActivity.this).create();
		alertDialog.setTitle("Erreur");
		alertDialog.setMessage(message);
		alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {

			}
		});

		alertDialog.show();
	}

	public void OnConfigClick(View v) {
		final Competition competition = (Competition) v.getTag();
		LayoutInflater factory = LayoutInflater.from(this);
		final View alertDialogView = factory.inflate(R.layout.equipe_config,
				null);

		// Création de l'AlertDialog
		AlertDialog.Builder adb = new AlertDialog.Builder(this);

		// On affecte la vue personnalisé que l'on a crée à notre
		// AlertDialog
		adb.setView(alertDialogView);

		// On donne un titre à l'AlertDialog
		adb.setTitle("Recevoir une notification");

		// On modifie l'icône de l'AlertDialog pour le fun ;)
		adb.setIcon(android.R.drawable.ic_dialog_alert);
		final Spinner s = (Spinner) alertDialogView.findViewById(R.id.spinner);

		ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
				R.array.notif, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s.setAdapter(adapter);

		// affecte un évènement
		adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					int min = CalendrierHelper.convertTominutes(s
							.getSelectedItem().toString());

					CalendrierHelper.saveMatchIntoCalenndar(competition,
							getApplicationContext(), min);

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
		adb.show();

	}

	public void OnHomeClick(View v) {

	}

}
